package com.pinyoumei.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.SplashBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.baidu.android.pushservice.PushManager;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 启动界面
 */
public class SplashActivity extends AppCompatActivity implements View.OnClickListener{
    private TimeCount timeCount;
    private RelativeLayout relative_nextstep;//点击下跳过
    private TextView text_num;
    private ImageView image_background;//背景图片 从后台加载的
    private Gson gson;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        StatusBarUtils.setTranslucentStatus(this);
        AppManager appManager = AppManager.getInstance();
        appManager.addActivity(this);
        gson = new Gson();
        initwidget();
        timeCount = new TimeCount(3 * 1000, 1000);//5s的一个定时器 间隔是1s
        timeCount.start();//启动计时器



        if (TextUtils.isEmpty(SPUtils.getWxKey(SplashActivity.this))){
            SPUtils.setWxKey(SplashActivity.this,"wxfcdbc78aac617cee");
        }


        String url = SPUtils.getSplashImageUrl(this);//先从本地获取
        if (!TextUtils.isEmpty(url)){
            Glide.with(SplashActivity.this).load( url).into(image_background);
        }
        ImageData();


        //获取加载页图片
//        getSplashImage(Constants.OEM_ID);
    }

    private void initwidget(){
        relative_nextstep = findViewById(R.id.relative_nextstep);
        relative_nextstep.setOnClickListener(this);
        text_num = findViewById(R.id.text_num);
        image_background = findViewById(R.id.image_background);
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.relative_nextstep://点击读秒
                timeCount.cancel();
                String str = SPUtils.getAppUserId(SplashActivity.this);
                com.pinyoumei.app.utils.LogUtils.e("Log","保存的app_user_id ="+str);
                if(TextUtils.isEmpty(SPUtils.getAppUserId(SplashActivity.this))){//判断用户有没有保存用户id 没有保存就进入登录页面
                        startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                    finish();
                    overridePendingTransition(0,0);
                }else{//如果用户保存了用户id 说明登录过 就直接进入主界面
                        startActivity(new Intent(SplashActivity.this,MainUIActivity.class));
                    finish();
                    overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                }
                break;
        }
    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
        timeCount.cancel();
    }
    //物理返回键的监听
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode == KeyEvent.KEYCODE_BACK  && event.getAction()==KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis() - exitTime)>2000){
                Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            }else{
                finish();
                //System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    //定时器类
    class TimeCount extends CountDownTimer{
         //构造方法
         public TimeCount(long millisInFuture, long countDownInterval){
             super(millisInFuture, countDownInterval);
         }
         @Override
         public void onTick(long millisUntilFinished){
             com.pinyoumei.app.utils.LogUtils.d("log",millisUntilFinished+"");
             text_num.setText("跳过 "+"0"+(millisUntilFinished/1000));
         }
         @Override
         public void onFinish(){
//             if(SPUtils.getIsFirstUse(SplashActivity.this)){//用户是否是第一安装使用
//                 startActivity(new Intent(SplashActivity.this,GuideActivity.class));
//                 finish();
//             }else{
                 String str = SPUtils.getAppUserId(SplashActivity.this);
                 com.pinyoumei.app.utils.LogUtils.e("Log","保存的app_user_id ="+str);
                 if(TextUtils.isEmpty(SPUtils.getAppUserId(SplashActivity.this))){//判断用户有没有保存用户id 没有保存就进入登录页面
                     startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                     finish();
                     overridePendingTransition(0,0);
                 }else{//如果用户保存了用户id 说明登录过 就直接进入主界面
                     if (SPUtils.isPush(SplashActivity.this)) {
                         ArrayList<String> tags = new ArrayList<>();
                         tags.add(SPUtils.getAppUserId(SplashActivity.this));
                         PushManager.setTags(getApplicationContext(), tags);

                         if (!TextUtils.isEmpty(SPUtils.getChannelId(SplashActivity.this))){
                             PushData(SPUtils.getChannelId(SplashActivity.this));
                         }

                     }
                     startActivity(new Intent(SplashActivity.this,MainUIActivity.class));
                     finish();
                     overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                 }
//             }
         }
    }


    private void ImageData( ) {

        Map<String,Object> map = new HashMap<>();
        map.put("oem_id",Constants.OEM_ID);
        map.put("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET));

        OkGo.<String>post( Constants.SPLASH_IMG)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);

                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        SplashBean splashBean = gson.fromJson(response.body(), SplashBean.class);
                        if (splashBean.getCode() >= 0 ){


                            String url = splashBean.getResult().getFlash_screen_img();
                            try{
                                Glide.with(SplashActivity.this).load(url).into(image_background);

                            }catch (Exception e){

                            }
                            SPUtils.saveSplashImageUrl(SplashActivity.this,url);

                        }else{
                            ToastUtils.showShort(splashBean.getMsg());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                });

    }


    private void PushData( String channel_id) {

        Map<String,Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(this));
        map.put("channel_id", channel_id);


        OkGo.<String>post( Constants.PUSH_BAIDU)
                .params("user_id",SPUtils.getAppUserId(this))
                .params("channel_id",channel_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);

                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        BaseBean financingBean = gson.fromJson(response.body(), BaseBean.class);
//                        if (financingBean.getCode() >= 0 ){
//
//
//                        }else{
//                            ToastUtils.showShort(financingBean.getMsg());
//                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                });

    }
}
